package com.duanyf.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duanyf.usercenter.mapper.UserMapper;
import com.duanyf.usercenter.model.domain.User;
import com.duanyf.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.duanyf.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author duanyf
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-05-28 22:34:13
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    private static final String SALT="yupi";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return -1;
        }
        if (userAccount.length() < 4) {
            return -1;
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            return -1;
        }

        /**
         * ^：表示匹配字符串的开头。
         * [a-zA-Z0-9_]：表示允许使用字母（大小写）、数字和下划线。
         * {3,20}：表示允许的字符数量在3到20之间。
         * $：表示匹配字符串的结尾。
         */
        String validPattern = "^[a-zA-Z0-9_]{3,20}$";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (!matcher.matches()) {
            return -1;
        }

        if (!userPassword.equals(checkPassword)) {
            return -1;
        }

        long count = userMapper.selectCount(new QueryWrapper<User>().eq("userAccount", userAccount));
        if (count > 0) {
            return -1;
        }

        String md5Password = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes(StandardCharsets.UTF_8));

        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(md5Password);
        boolean save = this.save(user);
        if (!save) {
            return -1;
        }

        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8 ) {
            return null;
        }

        /**
         * ^：表示匹配字符串的开头。
         * [a-zA-Z0-9_]：表示允许使用字母（大小写）、数字和下划线。
         * {3,20}：表示允许的字符数量在3到20之间。
         * $：表示匹配字符串的结尾。
         */
        String validPattern = "^[a-zA-Z0-9_]{3,20}$";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (!matcher.matches()) {
            return null;
        }

        String md5Password = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes(StandardCharsets.UTF_8));

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>()
                .eq("userAccount", userAccount).eq("userPassword", md5Password);
        User user = userMapper.selectOne(userQueryWrapper);

        if (Objects.isNull(user)){
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }

        //用户脱敏
        User safeUser=getSafeUser(user);

        //记录用户的登录态 :登陆成功，拿到登陆成功的session，并且设置用户信息
        request.getSession().setAttribute(USER_LOGIN_STATE,safeUser);

        return safeUser;
    }

    /**
     * 用户脱敏
     * @param originUser
     * @return
     */
    @Override
    public User getSafeUser(User originUser){
        User safeUser=new User();
        safeUser.setId(originUser.getId());
        safeUser.setUsername(originUser.getUsername());
        safeUser.setUserAccount(originUser.getUserAccount());
        safeUser.setAvatarUrl(originUser.getAvatarUrl());
        safeUser.setGender(originUser.getGender());
        safeUser.setPhone(originUser.getPhone());
        safeUser.setEmail(originUser.getEmail());
        safeUser.setUserStatus(originUser.getUserStatus());
        safeUser.setCreateTime(originUser.getCreateTime());
        safeUser.setUserRole(originUser.getUserRole());
        return safeUser;
    }
}




